<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            style="min-width: 230px"
            v-model="listQuery.name"
            placeholder="单号/姓名/手机号/案由/罪名"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            size="small"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-select
            v-model="listQuery.account_type"
            placeholder="银行账号"
            clearable
            size="small"
          >
            <el-option
              v-for="item in banks"
              :label="item.account"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddSale"
            >新增销售单</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="saleList"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="expand" align="center">
          <template slot-scope="scope">
            <el-tabs tab-position="left">
              <el-tab-pane label="收款单">
                <el-table
                  :data="scope.row.receipts"
                  border
                  v-if="scope.row.receipts.length > 0"
                  size="mini"
                >
                  <el-table-column
                    align="center"
                    label="单号"
                    prop="order_no"
                  />
                  <el-table-column
                    align="center"
                    label="时间"
                    prop="order_time"
                  />
                  <el-table-column
                    align="center"
                    label="科目"
                    prop="account_name"
                  />
                  <el-table-column
                    align="center"
                    label="收款账号"
                    prop="acc_type_name"
                  />
                  <el-table-column
                    align="center"
                    label="应收金额(元)"
                    prop="recv_money"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.recv_money }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="实收金额(元)"
                    prop="paid_money"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.paid_money }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="备注" prop="desc" />
                  <el-table-column
                    align="center"
                    label="经手人"
                    prop="user_name"
                  />
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="付款单">
                <el-table
                  :data="scope.row.pays"
                  border
                  v-if="scope.row.pays.length > 0"
                  size="mini"
                >
                  <el-table-column
                    align="center"
                    label="单号"
                    prop="order_no"
                  />
                  <el-table-column
                    align="center"
                    label="律师"
                    prop="person_name"
                  />
                  <el-table-column align="center" label="金额(元)" prop="money">
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="时间"
                    prop="order_time"
                  />

                  <el-table-column
                    align="center"
                    label="付款账号"
                    prop="acc_type_name"
                  />
                  <el-table-column
                    align="center"
                    label="科目"
                    prop="account_name"
                  />

                  <el-table-column align="center" label="备注" prop="desc" />
                  <el-table-column
                    align="center"
                    label="经手人"
                    prop="user_name"
                  />
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column align="center" label="销售单据号" prop="order_no">
          <template slot-scope="scope">
            <el-badge
              :value="scope.row.receipts.length"
              type="primary"
              :hidden="scope.row.receipts.length === 0 ? true : false"
              class="item"
            >
              <span style="margin-right: 8px">{{ scope.row.order_no }}</span>
            </el-badge>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="单据日期"
          prop="order_time"
          width="100"
        ></el-table-column>
        <el-table-column
          align="center"
          label="客户名称"
          prop="customer_name"
        ></el-table-column>
        <el-table-column
          align="center"
          label="案件名称"
          prop="case_name"
        ></el-table-column>
        <el-table-column
          align="center"
          label="会计科目"
          prop="account_name"
          width="100"
        ></el-table-column>
        <el-table-column
          align="center"
          label="收款账号"
          prop="acc_type_name"
          width="100"
        ></el-table-column>
        <el-table-column
          align="center"
          label="应收金额(元)"
          width="100"
          prop="recv_money"
          :formatter="dataFormatter"
        ></el-table-column>
        <el-table-column
          align="center"
          label="实收金额(元)"
          width="100"
          prop="paid_money"
          :formatter="dataFormatter"
        ></el-table-column>
        <el-table-column
          align="center"
          label="欠款金额(元)"
          width="100"
          prop="debt"
          :formatter="dataFormatter"
        ></el-table-column>
        <el-table-column
          align="center"
          label="支出金额(元)"
          width="100"
          prop="payment_money"
          :formatter="dataFormatter"
        ></el-table-column>
        <el-table-column
          align="center"
          label="经办人"
          prop="handler_name"
          width="100px"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
            ></el-button>
            <!-- <el-button
              type="success"
              size="mini"
              icon="el-icon-coin"
              @click="handleAssign(scope)"
              >律师费</el-button
            > -->
            <el-dropdown @command="handleCommand">
              <el-button type="success" size="mini">
                更多功能<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>

              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  icon="el-icon-plus"
                  :command="{ type: 'business', row: scope.row }"
                  >商务费</el-dropdown-item
                >
                <el-dropdown-item
                  icon="el-icon-plus"
                  :command="{ type: 'lawyer', row: scope.row }"
                  >律师费分配</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getSaleOrders"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="60%">
      <el-form
        :model="saleForm"
        :rules="saleFormRules"
        ref="saleFormRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="销售单据号"
              prop="order_no"
              v-if="dialogType === 'edit'"
            >
              <el-input
                type="text"
                v-model="saleForm.order_no"
                placeholder="销售单据号"
                maxlength="24"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据日期" prop="order_time">
              <el-date-picker
                v-model="saleForm.order_time"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择单据日期"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="客户名称" prop="customer">
          <el-select
            v-model="saleForm.customer"
            placeholder="选择客户名称"
            clearable
            @change="selectChange"
            filterable
            :filter-method="customerFilter"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.case_name
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="案件名称" prop="case_name">
          <el-input
            v-model="saleForm.case_name"
            placeholder="案件名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input
            v-model="saleForm.telephone"
            placeholder="手机号码"
            clearable
          />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="会计科目" prop="acc_title">
              <el-cascader
                v-model="selectedKeys"
                :options="accountList"
                :props="props"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账号" prop="account_type">
              <el-select
                v-model="saleForm.account_type"
                placeholder="收款账号"
                clearable
              >
                <el-option
                  v-for="item in banks"
                  :label="item.account"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="应收金额" prop="recv_money">
              <el-input
                v-model="saleForm.recv_money"
                placeholder="应收金额"
                clearable
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实收金额" prop="paid_money">
              <el-input
                v-model="saleForm.paid_money"
                placeholder="实收金额"
                clearable
                :disabled="dialogType == 'edit' ? true : false"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经办人" prop="handler">
              <el-select
                v-model="saleForm.handler"
                placeholder="经办人"
                clearable
              >
                <el-option
                  v-for="item in employees"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="saleForm.desc" placeholder="备注" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="发票">
          <el-input v-model="saleForm.bill" placeholder="发票" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveOrder">保存</el-button>
      </div>
    </el-dialog>
    <!-- 律师费分配 -->
    <el-dialog :visible.sync="dlgVisible" title="分配律师费" width="80%">
      <el-table :data="assignList" border size="small">
        <el-table-column
          label="序号"
          type="index"
          align="center"
        ></el-table-column>
        <!-- <el-table-column label="支付时间">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.order_time"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              clearable
            >
            </el-date-picker>
          </template>
        </el-table-column> -->
        <el-table-column label="律师">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.person"
              placeholder="选择律师"
              clearable
              size="small"
            >
              <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="职位">
          <template slot-scope="scope">
            <el-select v-model="scope.row.post" placeholder="职位" size="small">
              <el-option
                v-for="p in positions"
                :key="p.value"
                :label="p.label"
                :value="p.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="比例(%)">
          <template slot-scope="scope">
            <el-input v-model="scope.row.ratio" placeholder="比例" size="small">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="金额(元)">
          <template slot-scope="scope">
            <el-input v-model="scope.row.money" placeholder="金额" size="small">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.desc"
              placeholder="备注"
              size="small"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <!-- </el-form> -->
      <div slot="footer">
        <el-button type="danger" @click="dlgVisible = false" size="small"
          >取消</el-button
        >
        <el-button type="primary" @click="HandleAssignSave" size="small"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 商务费表单 -->
    <el-dialog :visible.sync="dlgBusVisible" title="商务费" width="600px">
      <el-form
        :model="feeForm"
        ref="feeFormRef"
        label-width="100px"
        label-position="right"
        style="padding: 0 30px"
      >
        <el-form-item label="销售单据号" prop="sale_order_code">
          <el-input
            type="text"
            v-model="feeForm.sale_order_code"
            placeholder="销售单据号"
            maxlength="24"
            disabled
          />
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input v-model="feeForm.money" placeholder="金额" clearable>
            <template slot="append"
              ><el-button type="default">元</el-button></template
            >
          </el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="feeForm.name" placeholder="姓名" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dlgBusVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveFee">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pickerOptions } from "@/utils/const";
import { mapGetters } from "vuex";
import { getParentsPath } from "@/utils/index";
import { getCurrentDate } from "@/utils/datetime";
import {
  getSaleOrders,
  addSaleOrder,
  updateSaleOrder,
  delSaleOrder,
  addPay,
  addBusinessFee,
  updateBusinessFee,
  delBusinessFee,
} from "@/api/sale";
import { getBanks } from "@/api/bank";
import { getCustomerList } from "@/api/customer";
import { getEmployeeList } from "@/api/employee";
import { get_account_titles } from "@/api/account";
import { positions } from "@/utils/const";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: undefined,
  order_no: "",
  order_time: getCurrentDate(),
  customer: undefined,
  case_name: "",
  telephone: "",
  acc_title: undefined,
  recv_money: 0,
  paid_money: 0,
  account_type: undefined,
  desc: "",
  bill: "",
  handler: null,
  user: undefined,
};

const assignForm = {
  id: undefined,
  order_no: "",
  order_time: getCurrentDate(),
  sale_order: null,
  person: null,
  acc_title: null,
  account_type: null,
  money: null,
  desc: "",
  user: null,
};

const defFeeForm = {
  id: undefined,
  sale_order: null,
  sale_order_code: "",
  name: null,
  money: null,
};

export default {
  name: "Sale",
  data() {
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value <= 0) {
          callback(new Error("必须大于零"));
        } else {
          callback();
        }
      }
    };
    const checkPaidMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value < 0) {
          callback(new Error("不能小于零"));
        } else {
          callback();
        }
      }
    };

    return {
      saleForm: Object.assign({}, defaultForm),
      saleFormRules: {
        order_time: [
          { required: true, message: "请输入单据日期", trigger: "blur" },
        ],
        customer: [{ required: true, message: "请选择客户", trigger: "blur" }],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        acc_title: [
          { required: true, message: "请选择会计科目", trigger: "blur" },
        ],
        account_type: [
          { required: true, message: "请选择收款账号", trigger: "blur" },
        ],
        recv_money: [{ validator: checkMoney, trigger: "blur" }],
        paid_money: [{ validator: checkPaidMoney, trigger: "blur" }],
      },
      feeForm: {},
      title: "销售单",
      customers: [],
      options: [],
      employees: [],
      accountList: [],
      banks: [],
      selectedKeys: [],
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      dialogVisible: false,
      dlgVisible: false,
      dlgBusVisible: false,
      dialogType: "new",
      saleList: [],
      assignList: [],
      fees: [],
      positions,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined,
        search_date: "",
        account_type: null,
      },
      pickerOptions,
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType === "edit"
        ? `编辑${this.title}`
        : `新增${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getSaleOrders(); //销售单
    this.getCustomers(); //客户
    this.getEmployeeList();
    this.getAccounts(); // 科目
    this.getBanks(); //收款账户列表
  },
  methods: {
    // 销售单列表
    getSaleOrders() {
      this.listLoading = true;
      getSaleOrders(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.saleList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取销售单数据失败");
          this.listLoading = false;
        });
    },

    ///更多功能
    handleCommand(command) {
      let type = command["type"];
      if (type == "lawyer") {
        this.handleAssign(command["row"]);
      } else if (type == "business") {
        this.handleBusiness(command["row"]);
      }
    },

    customerFilter(val) {
      console.log(val);
      // if(val==""){
      //   this.options = this.customers;
      //   return;
      // }
      this.options = this.customers.filter((item) => {
        if (item.name.indexOf(val) > -1) {
          return item;
        } else if (
          item.help_code &&
          item.help_code.toUpperCase().indexOf(val.toUpperCase()) > -1
        ) {
          return item;
        }
      });
    },

    handleBusiness(row) {
      if (row.fees.length > 0) {
        this.feeForm = row.fees[0];
      } else {
        this.feeForm = Object.assign({}, defFeeForm);
        this.feeForm.sale_order = row.id;
      }

      this.dlgBusVisible = true;

      this.feeForm.sale_order_code = row.order_no;
    },

    getCustomers() {
      getCustomerList()
        .then((res) => {
          this.options = res;
          this.customers = JSON.parse(JSON.stringify(this.options));

        })
        .catch((error) => {
          this.$message.error("获取客户数据失败");
          console.log(error.message);
        });
    },

    getEmployeeList() {
      getEmployeeList().then((res) => {
        this.employees = res;
      });
    },
    getAccounts() {
      get_account_titles({}).then((res) => {
        this.accountList = res;
      });
    },
    getBanks() {
      getBanks().then((res) => {
        this.banks = res;
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "recv_money" ||
          column.property === "paid_money" ||
          column.property === "debt"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });

      return sums;
    },
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "recv_money") {
        return row.recv_money.toFixed(2);
      } else if (column.property == "paid_money") {
        return row.paid_money.toFixed(2);
      } else if (column.property == "debt") {
        return row.debt.toFixed(2);
      } else if (column.property == "payment_money") {
        return row.payment_money.toFixed(2);
      } else {
        return cellValue;
      }
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getSaleOrders();
    },
    // 增加员工
    handleAddSale() {
      this.saleForm = Object.assign({}, defaultForm);
      this.options = this.customers;
      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.saleFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.saleForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(
          this.saleForm.acc_title,
          this.accountList
        );
        this.$refs["saleFormRef"].clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该销售单吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delSaleOrder(row.id);

          this.saleList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("销售单删除失败!");
        });
    },
    // 保存操作
    async SaveOrder() {
      this.$refs.saleFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.saleForm.user) {
            this.saleForm.user = this.uid;
          }
          res = await updateSaleOrder(this.saleForm);
          console.log(isEdit, res);
          const index = this.saleList.findIndex((v) => v.id === res.id);
          this.saleList.splice(index, 1, res);
        } else {
          this.saleForm.user = this.uid;
          res = await addSaleOrder(this.saleForm);
          const { id } = res;
          if (id > 0) {
            this.getSaleOrders();
          }
        }

        const {
          order_no,
          customer_name,
          telephone,
          recv_money,
          paid_money,
          account_name,
        } = res;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>单号: ${order_no}</div>
              <div>客户名称: ${customer_name}</div>
              <div>手机号: ${telephone}</div>
              <div>应收金额: ${recv_money}</div>
              <div>实收金额: ${paid_money}</div>
              <div>会计科目: ${account_name}</div>
            `,
          type: "success",
        });
      });
    },
    handleChange(value) {
      if (this.selectedKeys.length > 0) {
        this.saleForm.acc_title =
          this.selectedKeys[this.selectedKeys.length - 1];
      } else {
        this.saleForm.acc_title = undefined;
      }
    },
    selectChange(value) {
      const customer = this.customers.find((v) => v.id == value);
      this.saleForm.telephone = customer.telephone;
      this.saleForm.case_name = customer.case_name;
    },
    ///律师费分配
    handleAssign(row) {
      this.assignList = [];
      if (row.paid_money <= 0) {
        this.$message.warning("无律师费可分配!");
        return;
      }
      const lawyers = row.lawyers;
      if (lawyers.length == 0) {
        this.$message.warning("请为该客户分配律师");
        return;
      }
      const ratios = lawyers.map((item) => item.ratio * 0.01);

      const ratio_sum = ratios.reduce((prev, curr) => {
        return prev + curr;
      }, 0);

      let business_Fee = 0;

      if (row.fees.length > 0) {
        business_Fee = row.fees[0].money;
      }

      let paid_money = row.paid_money - business_Fee;

      const pay_sum = paid_money * ratio_sum.toFixed(2);

      if (pay_sum.toFixed(2) === row.assigned_money.toFixed(2)) {
        this.$message.warning("律师费已经分配完毕!");
        return;
      }
      this.dlgVisible = true;
      const money = paid_money - row.assigned_money;

      lawyers.forEach((item, index) => {
        let pay = Object.assign({}, assignForm);
        pay.sale_order = row.id;
        pay.person = item.employee;
        pay.post = item.post;
        pay.ratio = item.ratio;
        pay.money = (item.ratio * 0.01 * money).toFixed(2);
        pay.user = this.uid;

        this.assignList.push(pay);
      });
    },

    HandleAssignSave() {
      addPay(this.assignList)
        .then((res) => {
          this.dlgVisible = false;
          this.$notify({
            title: "Success",
            dangerouslyUseHTMLString: true,
            message: "律师费分配成功, 请到付款单里进行付款操作",
            type: "success",
          });
          this.getSaleOrders();
        })
        .catch((error) => {
          this.$message.error("律师费分配失败!");
        });
    },

    handleSaveFee() {
      this.$refs.feeFormRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;

        let isEdit = this.feeForm.id != undefined;

        if (isEdit) {
          res = await updateBusinessFee(this.feeForm);
        } else {
          res = await addBusinessFee(this.feeForm);
        }
        console.log(res);
        this.dlgBusVisible = false;
        this.getSaleOrders();
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-dropdown {
    margin-left: 10px;
  }
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }

  .item {
    margin-top: 8px;
  }
}
</style>